define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'editable'], function ($, undefined, Backend, Table, Form, undefined) {
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'yexam/question_type/index' + location.search,
                    add_url: 'yexam/question_type/add',
                    edit_url: 'yexam/question_type/edit',
                    del_url: 'yexam/question_type/del',
                    //table: 'question_type',
                },
                pageList : [20,40,60,80]
            });

            var table = $("#question_type");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                escape: false,
                pk: 'questid',
                sortName: 'questid',
                sortOrder:'asc',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'questsort', title: "排序",operate: false, editable: true},
                        {field: 'questid', title: __('Id')},
                        {field: 'questype', title: __('题型'),align: 'left',width:'60px'},
                        {field: 'questcode', title: __('题型代码'),align: 'left', editable: true},
                        {field: 'question_category', title: __('分类'),align: 'left',formatter:Table.api.formatter.search},
                        {field: 'create_time', title: __('创建时间'),operate: false},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            formatter:{

            },
            bindevent: function () {

                $("#c-package_ids").data("params", function (obj) {
                    return {custom: {category_id: $("#c-category_id").val()}};
                });

                Form.api.bindevent($("form[role=form]"));
            }
        }
        ,transfer: function () {
            //============= 检索按钮
            $(".bt-search").click(function () {
                Controller.request($("#subject_id").serializeArray());
                $(".transfer-result").html();
                $(".content-list").html();
                $(".btn-transfer").hide();
            });
            //======== 获取选择的分类
            $(document).on('change','.category-list-view',function () {
                let ids = $(this).val();
                Controller.request({type : 2, ids},this);
            });
            //====== 开始转换
            $(".btn-transfer").click(function () {
                Layer.confirm('立即提交题型转换',function () {
                    let data = $("#question-transfer-view-content").serializeArray();
                    data.push({
                        name : "start",
                        value : $("input[name=start]").val()
                    });
                    data.push({
                        name : "end",
                        value : $("input[name=end]").val()
                    });
                    Controller.request(data);
                });
            });
            //========= 选择题型代码
            $(document).on('change','.next',function () {
                let code = $(this).val();
                $(this).parent().parent().find('.code').val(code);
                $(".btn-transfer").show();
            });
        },
        //============ 请求封装
        request: function ( data,extend) {
            $.post("yexam/question_type/transfer",data,function (res) {
                if (res.code > 0)
                {
                    let type = res.msg;
                    if (type == 1)
                    {
                        let lists = res.data;
                        let html= '';
                        for (const listsKey in lists) {
                            html += `
                            <div class="row">
                <div class="col-sm-4">${lists[listsKey].questiontype}</div>
                <input type="hidden" name="item[${listsKey}][type]" value="${lists[listsKey].questiontype}">
                <input type="hidden" name="item[${listsKey}][code]" value="" class="code">
                <div class="col-sm-2">
                    <span class="badge bg-danger">${lists[listsKey].total}</span>
                </div>
                <div class="col-sm-2">
                    <select class="form-control category-list-view">
                        ${categoryList(lists[listsKey].category)}
                    </select>
                </div>
                <div class="col-sm-2">
                    <select class="form-control next"></select>
                </div>
            </div>
                            `;
                        }
                        $(".content-list").html(html);
                    }
                    else if (type == 2)
                    {
                        let tmp = "<option value=''>请选择</option>";
                        let lists = res.data;
                        for (const listsKey in lists) {
                            tmp += `<option value="${lists[listsKey].questcode}">${lists[listsKey].questype}</option>`;
                        }
                        $(extend).parent().siblings().find('.next').html(tmp);
                    }else if (type == 4) {
                        let tmp = "";
                        let lists = res.data;
                        for (const listsKey in lists) {
                            tmp += `
                            <div class="row fa-2x">
            <div class="col-md-2">${lists[listsKey].questiontype}</div>
            <div class="col-md-2">${lists[listsKey].total}</div>
        </div>
                            `;
                        }
                        $(".transfer-result").html(tmp);
                        Layer.closeAll();
                    }
                }else {
                    Layer.msg(res.msg);
                }
            });
            function categoryList(lists) {
                let tmp = '<option value="">请选择题型</option>';
                for (const listsKey in lists) {
                    tmp += `<option value="${lists[listsKey].question_type}">${lists[listsKey].category_name}</option>`;
                }
                return tmp;
            }
        },
        transfer_title: function () {
            //============= 检索按钮
            $(".bt-search").click(function () {
                Controller.questionRequest($("#form-info").serializeArray());
                $(".transfer-result").html();
                $(".content-list").html();
            });
            //====== 开始转换
            $(".btn-transfer").click(function () {
                Layer.confirm('立即提交题型转换',function () {
                    let data = $("#question-transfer-view-content").serializeArray();
                    $(".numbers-success").html(data.length-1)
                    Controller.questionRequest(data);
                });
            });
            /////// 全选
            $(".cekck-all").click(function () {
                let currentState = $(this).prop("checked");
                $(".content-list").find("input").each(function (item){
                    $(this).prop("checked",currentState);
                })
            });
            let currentObj = null;
            ////////////  编辑试题题目或内容
            $(document).on("dblclick",".col-sm-8,.col-sm-4",function () {
                $(this).find("textarea").show();
                $(this).find("span").hide();
                currentObj = this;
            });
            $(document).on("blur","textarea",function () {
                let content = $(this).val();
                let id = $(this).data('id');
                let field = $(this).data("field");
                //alert(id+content)
                $(currentObj).find("textarea").hide();
                $(currentObj).find("span").show().text(content);
                $.post("yexam/question_type/updateTitleSelect",{field,id,content},function (res) {
                    Layer.msg(res.msg);
                });
            })
        },
        questionRequest(data){
            $.post("yexam/question_type/transfer_title",data,function (res) {
                if(res.msg == 1){
                    let data = res.data;
                    let html = "";
                    data.forEach(function (item, index) {
                        html += `
                    <div class="row">
                    <div class="col-sm-4"><label>
                    <input type="checkbox" name="id[]" value="${item.id}">${item.question_name}</label>
                    </div>
                    <div class="col-sm-8">${Controller.HTMLDecode(item.questionselect)}</div>
                </div>`
                    });
                    $(".transfer-result").html(html);
                    Layer.closeAll();
                    return;
                }
                let data = res.data;
                let html = "";
                let numbers = 0;
                data.forEach(function (item, index) {
                    numbers++;
                    html += `
                    <div class="row">
                    <div class="col-sm-4"><label><input type="checkbox" name="id[]" value="${item.id}">
                    <span>${item.question_name}</span>
                    <textarea cols="80" data-id="${item.id}" style="display: none" data-field="question_name">${item.question_name}</textarea>
                    </label></div>
                    <div class="col-sm-8"><span>${Controller.HTMLDecode(item.questionselect)}</span><textarea  cols="140" style="display: none" data-id="${item.id}" data-field="questionselect">${item.questionselect}</textarea></div>
                </div>`
                });
                $(".numbers").html(numbers);
                $(".content-list").html(html);
            });
        },
        HTMLDecode(html) {
            let searchContent = $(".questionselect").val();
            var temp = document.createElement("div");
            (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html);
            var output = temp.innerHTML;
            temp = null;
            output = output.replace(searchContent,"<span style='font-weight: bold;color: rgb(255,0,0);font-size: 20px;'>"+searchContent+"</span>")
            return output
        }
    };
    return Controller;
});
